package com.zhentao.service.impl;

import com.zhentao.entity.User;
import com.zhentao.entity.UserProfile;
import com.zhentao.mapper.UserMapper;
import com.zhentao.mapper.UserProfileMapper;
import com.zhentao.service.UserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户扩展信息服务实现类
 */
@Service
public class UserProfileServiceImpl implements UserProfileService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserProfileMapper userProfileMapper;
    
    @Override
    public Map<String, Object> getUserProfile(Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 1. 查询用户基本信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 2. 设置基本信息
        result.put("userId", user.getUserId());
        result.put("nickname", user.getNickname());
        result.put("avatar", user.getAvatarUrl());
        result.put("gender", user.getGender());
        result.put("birthDate", user.getBirthDate() != null ? user.getBirthDate().toString() : null);
        
        // 计算并设置年龄
        Integer age = calculateAge(user.getBirthDate());
        result.put("age", age);
        
        // 3. 查询用户扩展信息
        UserProfile profile = userProfileMapper.selectByUserId(userId);
        
        if (profile != null) {
            // 扩展信息
            result.put("realName", profile.getRealName());
            result.put("idCard", profile.getIdCard());
            result.put("height", profile.getHeight());
            result.put("weight", profile.getWeight());
            result.put("star", profile.getStar());
            result.put("animal", profile.getAnimal());
            result.put("educationLevel", profile.getEducationLevel());
            result.put("schoolName", profile.getSchoolName());
            result.put("company", profile.getCompany());
            result.put("jobTitle", profile.getJobTitle());
            result.put("salaryRange", profile.getSalaryRange());
            result.put("maritalStatus", profile.getMaritalStatus());
            result.put("house", profile.getHouse());
            result.put("car", profile.getCar());
            result.put("hobby", profile.getHobby());
            result.put("privacySalary", profile.getPrivacySalary());
            result.put("privacyPhone", profile.getPrivacyPhone());
            result.put("authenticityScore", profile.getAuthenticityScore());
            
            // 认证状态
            result.put("isRealNameVerified", profile.getIsRealNameVerified() == 1);
            result.put("isEducationVerified", profile.getIsEducationVerified() == 1);
            result.put("isWorkVerified", profile.getIsWorkVerified() == 1);
            result.put("isMaritalVerified", profile.getIsMaritalVerified() == 1);
        } else {
            // 如果没有扩展信息，设置默认值
            result.put("authenticityScore", 0);
            result.put("isRealNameVerified", false);
            result.put("isEducationVerified", false);
            result.put("isWorkVerified", false);
            result.put("isMaritalVerified", false);
        }
        
        // VIP状态默认为false（后续可以从其他表查询）
        result.put("isVip", false);
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserProfile(UserProfile userProfile) {
        // 0. 数据验证
        if (userProfile.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 验证用户是否存在
        User user = userMapper.selectById(userProfile.getUserId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 1. 查询是否存在用户扩展信息
        UserProfile existProfile = userProfileMapper.selectByUserId(userProfile.getUserId());
        
        int result;
        LocalDateTime now = LocalDateTime.now();
        
        if (existProfile == null) {
            // 不存在则新增
            // 设置默认认证状态
            if (userProfile.getIsRealNameVerified() == null) userProfile.setIsRealNameVerified(0);
            if (userProfile.getIsEducationVerified() == null) userProfile.setIsEducationVerified(0);
            if (userProfile.getIsWorkVerified() == null) userProfile.setIsWorkVerified(0);
            if (userProfile.getIsMaritalVerified() == null) userProfile.setIsMaritalVerified(0);
            
            // 计算初始真实度评分
            int score = calculateAuthenticityScore(userProfile);
            userProfile.setAuthenticityScore(score);
            
            result = userProfileMapper.insert(userProfile);
            System.out.println("新增用户扩展信息 - 用户ID: " + userProfile.getUserId() + ", 初始评分: " + score);
        } else {
            // 存在则更新 - 创建完整的更新对象
            userProfile.setProfileId(existProfile.getProfileId());
            
            // 处理认证状态字段 - 只在没有传入值时保持原值
            if (userProfile.getIsRealNameVerified() == null) {
                userProfile.setIsRealNameVerified(existProfile.getIsRealNameVerified());
            }
            if (userProfile.getIsEducationVerified() == null) {
                userProfile.setIsEducationVerified(existProfile.getIsEducationVerified());
            }
            if (userProfile.getIsWorkVerified() == null) {
                userProfile.setIsWorkVerified(existProfile.getIsWorkVerified());
            }
            if (userProfile.getIsMaritalVerified() == null) {
                userProfile.setIsMaritalVerified(existProfile.getIsMaritalVerified());
            }
            
            // 处理其他字段 - 保持原值以避免null覆盖
            if (userProfile.getHouse() == null) {
                userProfile.setHouse(existProfile.getHouse());
            }
            if (userProfile.getCar() == null) {
                userProfile.setCar(existProfile.getCar());
            }
            if (userProfile.getEducationLevel() == null) {
                userProfile.setEducationLevel(existProfile.getEducationLevel());
            }
            if (userProfile.getSalaryRange() == null) {
                userProfile.setSalaryRange(existProfile.getSalaryRange());
            }
            if (userProfile.getMaritalStatus() == null) {
                userProfile.setMaritalStatus(existProfile.getMaritalStatus());
            }
            if (userProfile.getProvinceId() == null) {
                userProfile.setProvinceId(existProfile.getProvinceId());
            }
            if (userProfile.getCityId() == null) {
                userProfile.setCityId(existProfile.getCityId());
            }
            if (userProfile.getAreaId() == null) {
                userProfile.setAreaId(existProfile.getAreaId());
            }
            if (userProfile.getPrivacySalary() == null) {
                userProfile.setPrivacySalary(existProfile.getPrivacySalary());
            }
            if (userProfile.getPrivacyPhone() == null) {
                userProfile.setPrivacyPhone(existProfile.getPrivacyPhone());
            }
            if (userProfile.getVerifiedAt() == null) {
                userProfile.setVerifiedAt(existProfile.getVerifiedAt());
            }
            
            // 计算更新后的真实度评分
            int score = calculateAuthenticityScore(userProfile);
            userProfile.setAuthenticityScore(score);
            
            // 只调用一次updateById，包含评分更新
            result = userProfileMapper.updateById(userProfile);
            System.out.println("更新用户扩展信息 - 用户ID: " + userProfile.getUserId() + ", 更新后评分: " + score + ", 影响行数: " + result);
        }
        
        return result > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean forceUpdateUserProfile(UserProfile userProfile) {
        // 0. 数据验证
        if (userProfile.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 验证用户是否存在
        User user = userMapper.selectById(userProfile.getUserId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 1. 查询是否存在用户扩展信息
        UserProfile existProfile = userProfileMapper.selectByUserId(userProfile.getUserId());
        
        if (existProfile == null) {
            throw new RuntimeException("用户扩展资料不存在，请先创建基本资料");
        }
        
        // 2. 强制更新 - 允许设置null值清空字段
        userProfile.setProfileId(existProfile.getProfileId());
        
        // 计算更新后的真实度评分
        int score = calculateAuthenticityScore(userProfile);
        userProfile.setAuthenticityScore(score);
        
        // 使用自定义UPDATE语句强制更新所有字段（包括null值）
        int result = userProfileMapper.forceUpdateById(userProfile);
        System.out.println("强制更新用户扩展信息 - 用户ID: " + userProfile.getUserId() + ", 更新后评分: " + score + ", 影响行数: " + result);
        
        return result > 0;
    }
    
    /**
     * 计算真实度评分（0-100分）
     */
    private int calculateAuthenticityScore(UserProfile profile) {
        int score = 0;
        
        // 基本信息完整度（40分）
        if (profile.getRealName() != null && !profile.getRealName().isEmpty()) score += 10;
        if (profile.getIdCard() != null && !profile.getIdCard().isEmpty()) score += 10;
        if (profile.getHeight() != null && profile.getHeight() > 0) score += 5;
        if (profile.getWeight() != null && profile.getWeight() > 0) score += 5;
        if (profile.getStar() != null && !profile.getStar().isEmpty()) score += 5;
        if (profile.getAnimal() != null && !profile.getAnimal().isEmpty()) score += 5;
        
        // 学业工作信息（30分）
        if (profile.getEducationLevel() != null && profile.getEducationLevel() > 0) score += 10;
        if (profile.getSchoolName() != null && !profile.getSchoolName().isEmpty()) score += 5;
        if (profile.getCompany() != null && !profile.getCompany().isEmpty()) score += 10;
        if (profile.getJobTitle() != null && !profile.getJobTitle().isEmpty()) score += 5;
        
        // 认证状态（30分）
        if (profile.getIsRealNameVerified() != null && profile.getIsRealNameVerified() == 1) score += 10;
        if (profile.getIsEducationVerified() != null && profile.getIsEducationVerified() == 1) score += 10;
        if (profile.getIsWorkVerified() != null && profile.getIsWorkVerified() == 1) score += 5;
        if (profile.getIsMaritalVerified() != null && profile.getIsMaritalVerified() == 1) score += 5;
        
        return Math.min(score, 100);
    }
    
    /**
     * 计算年龄（改进版，处理边界情况）
     */
    private Integer calculateAge(LocalDate birthDate) {
        if (birthDate == null) {
            return null;
        }
        
        LocalDate now = LocalDate.now();
        
        // 检查出生日期是否在未来
        if (birthDate.isAfter(now)) {
            return 0;
        }
        
        // 使用Period计算准确年龄
        Period period = Period.between(birthDate, now);
        return period.getYears();
    }
}

